package com.jiamingZhao.pojo.info;

import cn.hutool.core.util.StrUtil;
import com.jiamingZhao.annotations.TableField;
import com.jiamingZhao.annotations.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@Accessors(chain = true)
@AllArgsConstructor
public class TableInfo {

	private static final String SET_PREFIX = "set";

	private String tableName;

	private Class<?> clazz;

	private Map<String, Method> entityMethodsMap;

	public TableInfo(Class<?> clazz) {
		this.clazz = clazz;
	}


	public TableInfo resolveTableName() {
		TableName tableAnno = clazz.getAnnotation(TableName.class);
		if (tableAnno != null && !tableAnno.value().isEmpty()) {
			tableName = tableAnno.value();
			return this;
		}
		tableName = StrUtil.toUnderlineCase(clazz.getSimpleName());
		return this;
	}

	public TableInfo handleEntityMethodsMap() {
		 entityMethodsMap = Arrays.stream(clazz.getMethods())
				.filter(method -> StrUtil.startWith(method.getName(), SET_PREFIX))
				.collect(Collectors.toMap(handleFiledName(), Function.identity()));
		 Arrays.stream(clazz.getDeclaredFields())
				 .filter(field -> field.isAnnotationPresent(TableField.class)
						 && StrUtil.isNotBlank(field.getAnnotation(TableField.class).value()))
				 .forEach(field -> {
					 Method method = entityMethodsMap.get(StrUtil.toUnderlineCase(field.getName()));
					 entityMethodsMap.remove(StrUtil.toUnderlineCase(field.getName()));
					 entityMethodsMap.put(field.getAnnotation(TableField.class).value(), method);
				 });
		 return this;
	}

	private  Function<Method, String> handleFiledName() {
		return ee -> StrUtil.toUnderlineCase(StrUtil.removePrefix(ee.getName(), SET_PREFIX));
	}

	public Collection<String> getColumnNameSet() {
		return entityMethodsMap.keySet();
	}
}